#!/bin/bash

# Deploy the complete contract update fix
echo "🚀 Deploying contract update fix..."

# Deploy frontend
echo "📦 Deploying frontend..."
scp -r out/* ubuntu@18.141.214.17:/var/www/html/admin-dashboard/

# Deploy backend files
echo "📦 Deploying backend files..."
scp ../backend/app/api/v1/endpoints/contract_updates_simplified.py ubuntu@18.141.214.17:/home/ubuntu/backend/app/api/v1/endpoints/
scp ../backend/app/api/v1/router.py ubuntu@18.141.214.17:/home/ubuntu/backend/app/api/v1/
scp ../backend/create_contract_updates_table.py ubuntu@18.141.214.17:/home/ubuntu/backend/

# Create database table
echo "🗄️ Creating database table..."
ssh ubuntu@18.141.214.17 "cd /home/ubuntu/backend && source venv/bin/activate && DTV_ENV=mainnet python create_contract_updates_table.py"

# Restart backend service
echo "🔄 Restarting backend service..."
ssh ubuntu@18.141.214.17 "cd /home/ubuntu/backend && pkill -f 'uvicorn.*9000' && sleep 5 && nohup bash start-mainnet.sh > restart.log 2>&1 &"

# Wait for service to start
echo "⏳ Waiting for services to start..."
sleep 15

# Test the endpoint
echo "🧪 Testing contract updates endpoint..."
ssh ubuntu@18.141.214.17 "curl -s -X GET 'http://localhost:9000/api/v1/contracts/admin/history' | jq '.' || echo 'Testing endpoint (may be empty initially)'"

echo "✅ Deployment complete!"
echo "🌐 Frontend: http://bn.detv.media/contract-updates"
echo "🌐 API: http://bn.detv.media/api/v1/contracts/admin/"